﻿using CAP.Model;
using DotNetCore.CAP;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using MySqlConnector;
using System;

namespace CAP.Demo.Controllers
{
    public class OrderController : Controller
    {
        private readonly ICapPublisher _capBus;
        private IOptions<AppSettings> _appSettings;

        public OrderController(ICapPublisher capBus, IOptions<AppSettings> appSettings)
        {
            _capBus = capBus;
            _appSettings = appSettings;
        }

        public IActionResult Create(int count = 1)
        {
            using (var connection = new MySqlConnection(_appSettings.Value.MySql))
            {
                using (var transaction = connection.BeginTransaction(_capBus, autoCommit: true))
                {
                    //业务代码
                    var id = Guid.NewGuid();
                    
                    var cmd = connection.CreateCommand();
                    cmd.CommandText = $"INSERT INTO tb_order(id,product_id,status)VALUES('{id}',1,'pending')";
                    cmd.Transaction = (MySqlTransaction)transaction.DbTransaction;
                    cmd.ExecuteNonQuery();

                    _capBus.Publish("order.create", new UpdateProductStock(id, Guid.Parse("99BA5433-DF5F-A898-C8E0-78B8BA55F251"), count), "order.status");
                    Console.WriteLine($"create order orderid={id} count={count}");
                }
            }
            return Ok();
        }

        [NonAction]
        [CapSubscribe("order.status")]
        public void UpdateStatus(UpdateOrderStatus model)
        {
            using (var connection = new MySqlConnection(_appSettings.Value.MySql))
            {
                connection.Open();
                var cmd = connection.CreateCommand();
                cmd.CommandText = $"update tb_order set status='{(model.Success ? "successed" : "failed")}' where id='{model.OrderID}'";
                cmd.ExecuteNonQuery();
                Console.WriteLine($"update order status orderid={model.OrderID} success={model.Success}");
            }
        }
    }
}